package com.sulent.frame.file.utils;

import io.minio.ListObjectsArgs;
import io.minio.MinioClient;
import io.minio.Result;
import io.minio.errors.*;
import io.minio.messages.Item;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidKeyException;
import java.util.Iterator;

public class MinioPagination {

  public static void main(String[] args)
          throws NoSuchAlgorithmException, InvalidKeyException, IOException, ServerException, InsufficientDataException, ErrorResponseException, InvalidResponseException, XmlParserException, InternalException {
    // 创建一个MinIO客户端实例
    MinioClient minioClient =
        MinioClient.builder()
            .endpoint("https://play.min.io")
            .credentials("YOUR_ACCESS_KEY", "YOUR_SECRET_KEY")
            .build();

    // 指定要列出对象的存储桶名称
    String bucketName = "my-bucket";

    // 初始化marker为空
    String marker = null;

    // 每次获取的对象数量
    int objectsPerPage = 10;

    while (true) {
      ListObjectsArgs build = ListObjectsArgs.builder().marker(marker).bucket(bucketName).maxKeys(objectsPerPage).build();
      Iterable<Result<Item>> objects =
          minioClient.listObjects(build);
      Iterator<Result<Item>> iterator = objects.iterator();

      // 处理当前页的对象
      while (iterator.hasNext()) {
        Result<Item> result = iterator.next();
        Item item = result.get();
        System.out.println(item.objectName());
      }

      // 如果获取到的对象数量小于objectsPerPage，说明已经获取到了所有对象
      if (iterator.hasNext()) {
        break;
      }

      // 更新marker为当前页的最后一个对象名称
      marker = iterator.next().get().objectName();
    }
  }
}